﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace YServer
{
    public class SocketModelDEncode
    {
        /// <summary>
        /// 传输模型解码委托 （socketmodel ）
        /// </summary>
        public static object SocketModelDe(byte[] value)
        {
            SocketModel model = new SocketModel();

            ByteArray ba = new ByteArray(value);

            byte t;
            int a, c;

            ba.read(out t);
            model.type = t;

            ba.read(out a);
            model.area = a;

            ba.read(out c);
            model.command = c;

            //如果可以继续读取，则传输 model.transModel 不为空
            if (ba.Readable) {
                byte[] date=new byte[ba.Length-ba.Position];
                ba.read(out date, date.Length);
                object result = SerializationUtil.DeSerialization(date);
                model.transModel = result;
            }

            return model;
        }

        /// <summary>
        /// 传输模型编码委托 （socketmodel）
        /// </summary>
        public static byte[] SocketModelEn(object m) {
            SocketModel model = m as SocketModel;
            //创建字节数组流对象
            ByteArray ba = new ByteArray();

            ba.write(model.type);
            ba.write(model.area);
            ba.write(model.command);

            //传输对象不为空，先用C#序列化方法把对象序列化，然后在写入 ba 中
            if (model.transModel != null) {
                byte[] r = SerializationUtil.Serialization(model.transModel);
                ba.write(r); 
            }

            byte[] date = ba.GetBuffer();
            ba.Close();
            return date;

        }
    }
}
